package com.x.erp.manage;

import com.x.erp.dao.InsuranceOrderDao;
import com.x.erp.dao.InsuranceOrderGoodsDao;
import com.x.erp.model.InsuranceOrder;
import com.x.erp.model.InsuranceOrderGoods;
import com.x.framework.manage.BaseManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class InsuranceOrderManage extends BaseManage {

	@Autowired
	private InsuranceOrderDao insuranceOrderDao; // 延保订单dao

	@Autowired
	private InsuranceOrderGoodsDao insuranceOrderGoodsDao;

	public InsuranceOrder insertInsuranceOrder(InsuranceOrder insuranceOrder) throws Exception {
		Date cDate = new Date();
		insuranceOrder.setOrderCreateTime(cDate);
		insuranceOrder.setOrderUpdateTime(cDate);
		// 生成订单编号
		createOrderNo(insuranceOrder);
		List<InsuranceOrderGoods> orderGoodsList = insuranceOrder.getOrderGoodsList();
		insuranceOrder = this.insert(insuranceOrder);
		// 调用接口，插入多条订单商品数据
		insuranceOrderGoodsDao.insertInsuranceOrderGoodsList(insuranceOrder, orderGoodsList);
		return insuranceOrder;
	}

	// 生成订单号
	private void createOrderNo(InsuranceOrder insuranceOrder) throws Exception {
		String orderNo = null;
		StringBuffer stringBuffer = null;
		Random random = new Random();
		// 保证生成的订单号唯一
		while (true) {
			stringBuffer = new StringBuffer(this.getCurrentDate(0, "yyyyMMdd"));
			for (int i = 0; i < 6; ++i) {
				stringBuffer.append(random.nextInt(10));
			}
			orderNo = stringBuffer.toString();
			InsuranceOrder orderTemp = new InsuranceOrder();
			orderTemp.setOrderNo(orderNo);
			orderTemp = insuranceOrderDao.selectInsuranceOrder(orderTemp);
			if (orderTemp == null) {
				break;
			}
		}
		insuranceOrder.setOrderNo(orderNo);
	}
}
